module.exports = {
	// 登陆
	async login() {
		const { mobile, code } = this.$dx.request.post();
		if (!this.$dx.utils.isMobile(mobile)) {
			this.$dx.error('手机号码格式错误');
		}
		//校验验证码
		await this.$dx.service.verifyCodes.checkVerifyCode(mobile,code);
		// 登录
		let user = await this.$dx.service.user.where('mobile', mobile).find();
		if (!user) {
			// 创建用户
			return await this.$dx.service.user.createByMobile(mobile);
		}
		// 用户已禁用
		if (user.status !== 0) {
			this.$dx.error('用户已禁用');
		}
		// 判断是否有应用权限
		if (user.dcloud_appid.length && !user.dcloud_appid.includes(this.$dx.request.appId)) {
			await this.$dx.service.logs.addLoginLog(user._id, user.username, 'login', 0, user.mobile, user.email);
			this.$dx.error('账号没有应用权限');
		}
		return await this.$dx.service.user.loginByUser(user);
	},
	// 发送验证码
	async sendCode({ smsKey, smsSecret, templateId, name, codeExpiresIn }, phone, code) {
		const res = await uniCloud.sendSms({
			appid: this.$dx.request.appId,
			smsKey,
			smsSecret,
			phone,
			templateId, // 请替换为自己申请的模板id
			data: {
				name,
				code,
				expMinute: '' + Math.round(codeExpiresIn / 60),
			},
		});
		return res.code === 0 && res.success === true;
	},
};
